<?php

namespace apiend\models;

use Yii;
use common\base\Model;
use apiend\models\User;
use common\models\user\UserConnect;
use common\models\user\UserMeta;
use common\helpers\IpHelper;
use yii\db\Exception;

/**
 * 第三方登录
 * ForgetForm 
 */
class ThirdPartyForm extends Model {

    public $client;
    public $openid;
    public $data;
    //
    private $_user = null;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['client', 'openid', 'data'], 'required'],
        ];
    }

    /**
     * Finds user by [[username]]
     *
     * @return \api\models\UserCompatibleModel|null
     */
    protected function getConnect() {
        if ($this->_user === null) {
            $this->_user = UserConnect::findOrNew([
                'openid' => $this->openid,
                'client' => $this->client,
            ]);
        }
        return $this->_user;
    }

    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function bind() {
        if (!$this->validate()) {
            $this->dumpError('重置密码校验失败');
        }
        $connect = $this->getConnect();

        if ($connect->user_id) {
            return $connect->user;
        }

        $data = [
            'nickname' => null,
            'avatar' => null,
            'gender' => 0
        ];
        
        if ($this->client == 'qq') {
            $userinfo = \yii\helpers\Json::decode($connect->data, false);
            $data = [
                'nickname' => $userinfo->nickname,
                'avatar' => $userinfo->figureurl_qq_2,
                'gender' => array_search($userinfo->gender, ['未知', '男', '女'])
            ];
        }

        $user = new User();
        $user->username = 'TD' . uniqid();
        $user->generateAuthKey();

        $meta = new UserMeta();
        $meta->setAttributes($data);
        $meta->ip = IpHelper::ip();

        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$user->save()) {
                throw new Exception('账号信息创建失败');
            }
            $meta->id = $user->id;
            if (!$meta->save()) {
                throw new Exception('用户基本信息保存失败');
            }
            $connect->user_id = $user->id;
            if (!$connect->save()) {
                throw new Exception('connect信息创建失败');
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->dumpError($e->getMessage());
        }

        return $connect->user;
    }

}
